from tkinter import *
from tkinter.ttk import *
from tkinter import font, filedialog
from markdown2 import Markdown
from tkhtmlview import HTMLLabel
import os


class HelpdocWindow(Toplevel):
    def __init__(self, masterUI, parentWin):
        Toplevel.__init__(self)
        self.masterUI = masterUI
        self.parentWin = parentWin

        # 转换器对象
        self.md2html = Markdown()

        # 帮助文档路径
        self.helpdocPath = './helpdocs'

        self.myfont = font.Font(family="Helvetica", size=14)
        self.init_curWindow()

    def init_curWindow(self):
        self.title("控制器检测帮助文档")
        self.geometry('900x800+300+300')

        self.init_notebook()

    def init_notebook(self):
        # 创建notebook
        self.tabControl = Notebook(self)
        self.tabControl.pack(fill=BOTH, expand=1)

        helpdocs = {}
        filenames = os.listdir(self.helpdocPath)
        for file in filenames:
            print(file)
            if os.path.splitext(file)[1] == '.md':
                # print(file, '是md文件')
                curfile_path = os.path.join(self.helpdocPath, file)
                helpdocs[file] = curfile_path
        # print(helpdocs)

        for file, path in helpdocs.items():
            print(file)
            curTabFrame = Frame(self.tabControl)
            self.tabControl.add(curTabFrame, text=file)
            curhelpWindow = HTMLLabel(
                curTabFrame,  width="1", background="white", html="<h1>帮助展示页</h1>")
            curhelpWindow.pack(fill=BOTH, expand=1, side=RIGHT)
            curhelpWindow.fit_height()

            with open(path, 'r', encoding='utf-8') as f:
                if f:
                    markdownText = f.read()
                    # print(markdownText)
                    # 修正图片路径，调整为解释器运行位置根路径
                    markdownText = markdownText.replace(
                        'md_asserts', './helpdocs/md_asserts')
                    html = self.md2html.convert(markdownText)
                    print(html)
                    curhelpWindow.set_html(html)


def helpdoc_window(masterUI, parentWin):
    HelpdocWindow(masterUI=masterUI, parentWin=parentWin)


def main():
    root = Tk()
    app = HelpdocWindow(root)
    app.mainloop()


if __name__ == '__main__':
    main()
